package com.example.kafkademo.producer;

import com.example.kafkademo.common.MessageEntity;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFutureCallback;

public class ProducerCallback implements ListenableFutureCallback<SendResult<String, MessageEntity>> {

    private final Long startTime;

    private final String key;

    private final MessageEntity message;

    public ProducerCallback(Long startTime, String key, MessageEntity message) {
        this.startTime = startTime;
        this.key = key;
        this.message = message;
    }

    @Override
    public void onFailure(Throwable throwable) {
        System.out.println("消费失败");
        throwable.printStackTrace();
    }

    @Override
    public void onSuccess(SendResult<String, MessageEntity> result) {
        if (result == null) {
            return;
        }

        Long elaspedTime = System.currentTimeMillis() - startTime;
        RecordMetadata metadata = result.getRecordMetadata();
        if (metadata != null) {
            System.out.println("消费成功,耗时:" + elaspedTime);
        }
    }
}
